package com.kungfuhacking.wristbandpro.mqtt;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.kungfuhacking.wristbandpro.utils.CommonUtils;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import mqttresource.MqttClient;

/**
 * 聊天服务service
 * Created by Aaron on 17/5/16.
 */

public class MQTTService extends Service {

    private Disposable loopSubscribe;
    private String TAG = getClass().getSimpleName();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //提高优先级为可视进程
        Notification notification = new Notification();
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        startForeground(1, notification);
        flags = Service.START_FLAG_REDELIVERY;

        Log.e(TAG, "==onStartCommand==");

        checkConnection();

        return super.onStartCommand(intent, flags, startId);

    }

    SharedPreferences sp;

    public void checkConnection() {

        //每隔30秒检查一次mqtt连接情况
        loopSubscribe = Observable.interval(0, 30, TimeUnit.SECONDS).map(new Function<Long, Integer>() {
            @Override
            public Integer apply(Long aLong) throws Exception {

                LogUtil.d(TAG, " 检查mqtt连接情况 " + Thread.currentThread().getName());

                //网络不可用
                if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
                    return 1;
                }

                MqttClient mqttClient = MqttManager.getInstance().getMqttClient();

                if (sp == null)
                    sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);

                if (sp.getBoolean(MqttConstant.INTERVAL_CONNET_MQTT, true)) {
                    if (mqttClient == null || !mqttClient.isConnected())
                        MqttManager.getInstance().getMqttIp(getApplicationContext());
                } else onDestroy();


                return 1;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);//取消一直存在
        if (loopSubscribe != null)
            loopSubscribe.isDisposed();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
